﻿using System.ComponentModel;
using System.Net;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Altairis.Web.UI.WebControls {

    public enum IpAddressType {
        IPv4,   // Internet Protocol version 4 address required
        IPv6,   // Internet Protocol version 6 address required
        Any     // Any IP version accepted
    }

    [ToolboxData("<{0}:IpAddressValidator runat=server></{0}:IpAddressValidator>")]
    public class IpAddressValidator : BaseValidator {

        [Description("The required version of IP address. Most likely the family you want is IPv4.")]
        public IpAddressType AddressType {
            get { return (IpAddressType)(this.ViewState["AddressType"] ?? IpAddressType.IPv4); }
            set { this.ViewState["AddressType"] = value; }
        }

        protected override bool EvaluateIsValid() {
            // Get string to validate
            string s = this.GetControlValidationValue(this.ControlToValidate);

            // Always respond to empty string as valid
            if (string.IsNullOrEmpty(s)) return true;

            // Try to parse string as IP address
            IPAddress ip;
            bool result = IPAddress.TryParse(s, out ip);
            if (!result) return false;

            // Check version of IP address
            switch (this.AddressType) {
                case IpAddressType.IPv4:
                    return ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork;
                case IpAddressType.IPv6:
                    return ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6;
                default:    // Any
                    return true;
            }
        }
    }
}